package com.cqdev.washer.biz.service.impl;

import com.cqdev.washer.biz.model.DbConfigBO;
import com.cqdev.washer.biz.service.DbConfigService;
import com.cqdev.washer.infra.entity.DbConfig;
import com.cqdev.washer.infra.enums.DBDriverType;
import com.cqdev.washer.infra.mapper.DbConfigMapper;
import com.cqdev.washer.infra.util.keygen.KeyGenerators;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * @author yunfei.li
 *         类描述: TODO
 *         日期： 2018/7/9
 */
@Service
public class DbConfigServiceImpl implements DbConfigService {

    private final DbConfigMapper dbConfigMapper;

    public DbConfigServiceImpl(DbConfigMapper dbConfigMapper) {
        this.dbConfigMapper = dbConfigMapper;
    }

    @Override
    public DbConfigBO getOne(Long id) {
        DbConfig dbConfig = dbConfigMapper.selectByPrimaryKey(id);
        return convertDbConfig(dbConfig);
    }

    @Override
    public void saveOrUpdate(DbConfigBO dbConfigBO) {
        if (dbConfigBO.getId() == null) {
            save(dbConfigBO);
        } else {
            update(dbConfigBO);
        }
    }

    private void update(DbConfigBO dbConfigBO) {

        DbConfig dbConfigDO = new DbConfig(
                dbConfigBO.getId(),
                dbConfigBO.getDbDriverType().name(),
                dbConfigBO.getUrl(),
                dbConfigBO.getDbName(),
                dbConfigBO.getUsername(),
                dbConfigBO.getPassword(),
                null,
                new Date()
        );
        dbConfigMapper.updateByPrimaryKey(dbConfigDO);
    }

    private void save(DbConfigBO dbConfigBO) {
        DbConfig dbConfig = new DbConfig(
                KeyGenerators.generateKeyToLong(),
                dbConfigBO.getDbDriverType().name(),
                dbConfigBO.getUrl(),
                dbConfigBO.getDbName(),
                dbConfigBO.getPassword(),
                dbConfigBO.getUsername(),
                new Date(),
                new Date()
        );
        dbConfigMapper.insert(dbConfig);
    }


    private DbConfigBO convertDbConfig(DbConfig dbConfig) {

        return new DbConfigBO(
                dbConfig.getId(),
                dbConfig.getUrl(),
                dbConfig.getUsername(),
                dbConfig.getPassword(),
                dbConfig.getDbName(),
                DBDriverType.valueOf(dbConfig.getType())
        );
    }
}
